package com.caineng.zhaobiao.zbapi.utils.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.caineng.zhaobiao.zbapi.dao.CaiBaseUserKeywordDao;
import com.caineng.zhaobiao.zbapi.dao.CaiBaseUserPushMessageDao;
import com.caineng.zhaobiao.zbapi.dao.CaiZhaobiaoDao;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUserExtend;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUserKeyword;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUserPushMessage;
import com.caineng.zhaobiao.zbapi.domain.CaiZhaobiao;
import com.caineng.zhaobiao.zbapi.utils.ChineseSegment;
import com.caineng.zhaobiao.zbapi.utils.UniPushUtils;
import com.caineng.zhaobiao.zbapi.utils.async.AsyncManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 定时任务
 * @author liandyao
 * @date 2021/7/9 21:28
 */
@EnableScheduling
@Service
@Lazy(false)
@Slf4j
public class TaskConfig {


    @Autowired
    private MongoTemplate mongoTemplate ;

    @Autowired
    private CaiZhaobiaoDao zhaobiaoDao ;

    @Autowired
    private CaiBaseUserKeywordDao keywordDao;

    @Autowired
    private CaiBaseUserPushMessageDao pushMessageDao ;


    /**
     * 10分钟执行一次,上一次执行完成之后10分钟再执行
     */
    @Scheduled(fixedDelay=1000*60*10)

    public void auditPoster(){
        segAreaName();
    }

    /**
     * 有些省份的数据只有省有值,城市没有值,所以利用这个方法将城市赋值
     * 利用分词工具将地区赋值
     */
    private void segAreaName() {
        log.info("zb-api-自动任务执行.............");

        Query query = new Query();
        Criteria criteria = new Criteria();

        ////城市如果为空 只查询今天的
        Pattern pattern = Pattern.compile("^.*" + DateUtil.today() + ".*$", Pattern.CASE_INSENSITIVE);

        criteria.andOperator(Criteria.where("createTime").regex(pattern),Criteria.where("areaName").is(null));

        query.addCriteria(criteria);

        List<CaiZhaobiao> list =mongoTemplate.find(query, CaiZhaobiao.class);
        log.info("查询到没有地区的招标数据是:"+list.size());
        for(CaiZhaobiao zb:list){
            log.info("===>"+zb.getProjectName()+"  "+zb.getPublishTime());
            //标题
            String title = zb.getNoticeTitle();
            List<String> segs = ChineseSegment.segment(title);
            for(String seg:segs){
                log.info("分词: "+seg);
                AppStartRunner.Address addr = MapUtil.get(AppStartRunner.areaNameMap,seg,AppStartRunner.Address.class);
                if(addr != null) {
                    if (addr.getAreaName().contains("市辖区") || addr.getAreaName().equals("直辖县")) {
                        zb.setAreaName(addr.getAreaName());//区县名称,例如直辖市,北京->朝阳区,湖北省->神龙架
                    } else {
                        zb.setAreaName(addr.getCityName());//城市名称,例如,江西省->南昌市
                    }
                    updateZhaobiaoAreaName(zb.getId(),zb.getAreaName());
                    log.info("结果: "+zb.getAreaName());
                    //第一个分词如果有,后面的就不需要匹配了
                    break ;
                }

            }
            if(StrUtil.isBlank(zb.getAreaName())){
                //循环完成时,还没有匹配,那就直接省会城市
                String shenghui=MapUtil.get(AppStartRunner.shenghuiMap,zb.getProvinceName(),String.class);
                log.info(zb.getProvinceName()+"    "+shenghui);
                zb.setAreaName(shenghui);
                updateZhaobiaoAreaName(zb.getId(),zb.getAreaName());
            }


        }
    }

    /**
     * 修改区域
     * @param id
     * @param areaName
     */
    public void updateZhaobiaoAreaName(String id ,String areaName){

        //更新cai_zhaobiao表
        mongoTemplate.upsert(Query.query(Criteria.where("id").is(id)), Update.update("areaName",areaName),"cai_zhaobiao");
        //同步更新cai_zhaobiao_property表,因为更新此表时,有可能地区数据还没有
        mongoTemplate.upsert(Query.query(Criteria.where("_id").is(id)), Update.update("cityName",areaName),"cai_zhaobiao_property");

    }


    class Zhaobiao{
        String areaName;
        String title;
        String precise;
        String noticeType;
        String busId ;
    }

    /**
     * 一天执行一次推送
     * 每天上午12点05执行一次
     */
    @Scheduled(cron = "0 05 12 * * ?")
    //@Scheduled(fixedDelay=100000)
    public void pushClientId2(){
        //查询今天所有的招标信息 createTime
        String curDate = DateUtil.today();
        log.info("推送今天的日期"+curDate);
        List<CaiZhaobiao> list = mongoTemplate.find(Query.query(Criteria.where("createTime").gte(curDate)), CaiZhaobiao.class);
        //根据用户的订阅,和当前的招标信息匹配,然后推送消息
        List<CaiBaseUserKeyword> listKeywords = keywordDao.findAll();
        Map<String,Zhaobiao> usersMap = new HashMap<String,Zhaobiao>();
        list.forEach(zb->{
            String precise = zb.getPrecise(); //分类
            String noticeTitle = zb.getNoticeTitle();//标题

            String provinceName = zb.getProvinceName();
            String cityName = zb.getAreaName();

            listKeywords.forEach(user->{

                List<String> keyWords = user.getKeyWord();//用户订阅的关键字
                List<String> keyAddress = user.getAreaName();//用户订阅的地区
                /*
                根据用户订阅的关键字和订阅的地区进行推送,如果没有进行订阅,则不会推送
                 */
                if(StrUtil.containsAny(noticeTitle+precise,  keyWords.toArray(new String[keyWords.size()])) && StrUtil.containsAny(provinceName+cityName,  keyAddress.toArray(new String[keyAddress.size()]))){
                    Zhaobiao zbVo = new Zhaobiao();
                    zbVo.areaName=StrUtil.emptyIfNull(zb.getAreaName());
                    zbVo.title=noticeTitle;
                    zbVo.precise=precise;
                    zbVo.busId=zb.getId();
                    zbVo.noticeType = StrUtil.emptyIfNull(zb.getNoticeType());
                    usersMap.put(user.getUserId(),zbVo);//利用map,保证每个用户每天只推送一次
                    log.info("准备开始推送:"+zbVo.title+"  推送给:"+user.getUserId());
                }
            });
        });

        Set<String> setUsers = usersMap.keySet();
        log.info("总共有:"+setUsers.size()+"人需要推送");
        setUsers.forEach(userId->{
            //查询到clientId,然后进行发送
            CaiBaseUserExtend userExtend = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), CaiBaseUserExtend.class);
            if(userExtend!=null){
                String clientId = userExtend.getClientId();
                Zhaobiao zb = usersMap.get(userId);
                //延迟推送,太快可能会导致uniapp接口响应不了
                AsyncManager.me().execute(new TimerTask() {
                    @Override
                    public void run() {
                        //加入消息表中,下次还可以再看推送的消息
                        CaiBaseUserPushMessage p = new CaiBaseUserPushMessage();
                        p.setUserId(userId);
                        p.setCreateTime(System.currentTimeMillis()/1000);
                        p.setBusId(zb.busId);
                        p.setType("zhaobiao");
                        p.setTitle("您有最新的招投标信息,请查收");
                        p.setContent(zb.title);
                        pushMessageDao.insert(p);
                    }
                },10);

                //延迟推送,太快可能会导致uniapp接口响应不了
                AsyncManager.me().execute(new TimerTask() {
                    @Override
                    public void run() {
                        UniPushUtils.pushClientId(clientId,"您有最新的招投标信息,请查收",zb.title,"zhaobiao",zb.busId);
                    }
                },200);
            }
        });

    }


    /**
     * 测试推送功能
     * 10秒推送一次
     */
    /*@Scheduled(fixedDelay=10000)
    public void testPush2(){
        //查询今天所有的招标信息 createTime
        String userId = "6389181137978432";
        //查询到clientId,然后进行发送
        CaiBaseUserExtend userExtend = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), CaiBaseUserExtend.class);
        if(userExtend!=null){
            String clientId = userExtend.getClientId();

            //延迟推送,太快可能会导致uniapp接口响应不了
            AsyncManager.me().execute(new TimerTask() {
                @Override
                public void run() {
                    //加入消息表中,下次还可以再看推送的消息
                    CaiBaseUserPushMessage p = new CaiBaseUserPushMessage();
                    p.setUserId(userId);
                    p.setCreateTime(System.currentTimeMillis()/1000);
                    p.setBusId("1_31_513688");
                    p.setType("zhaobiao");
                    p.setTitle("您有最新的招投标信息,请查收");
                    p.setContent("闵行区邻松圩区东河泾泵闸改造工程");
                    pushMessageDao.insert(p);
                }
            },10);

            //延迟推送,太快可能会导致uniapp接口响应不了
            AsyncManager.me().execute(new TimerTask() {
                @Override
                public void run() {
                    UniPushUtils.pushClientId(clientId,"您有最新的招投标信息,请查收","闵行区邻松圩区东河泾泵闸改造工程","zhaobiao","1_31_513688");
                }
            },200);
        }


    }*/

    public static void main(String[] args) {
        int qq=62476489;
        double d = Math.sqrt(Math.sqrt(qq));
        System.out.println(d+"    "+Math.sqrt(qq));

    }


}
